﻿using System;
using System.Runtime.Caching;

namespace SystmicFunction.Public.CacheService
{
    public static class LocalMemoryCache
    {
        private static readonly MemoryCache LocalMemory = MemoryCache.Default;

        /// <summary>
        /// 设置本地缓存，上层捕获并封装异常
        /// Eg:    
        ///     Key:User-Userid 保存用户主键
        ///     Key:UserPermission-Userid 保存用户权限值
        /// </summary>
        /// <param name="key">唯一关键字</param>
        /// <param name="data">数据</param>
        /// <param name="dateTimeOffset">过期时间为NULL，默认时间为30min</param>
        /// <returns></returns>
        public static void SetCache(string key, object data, DateTimeOffset dateTimeOffset)
        {
            /*
            LocalMemory.Get("获取缓存项的唯一标识符", "缓存中的一个添加了缓存项的命名区域，默认为NULL");
            CacheItemPolicy cacheItemPolicy = new CacheItemPolicy();
            cacheItemPolicy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(30);//.AddMinutes(30);
            LocalMemory.Set("00-00-00-00-00", DateTime.Now+"Data00", cacheItemPolicy,null);
            LocalMemory.Set("00-00-00-00-01", DateTime.Now+"Data01", cacheItemPolicy,null);
             */
            
            LocalMemory.Set(key, data, dateTimeOffset);
        }

        /// <summary>
        /// 设置本地缓存，上层捕获并封装异常
        /// Eg:    
        ///     Key:User-Userid 保存用户主键
        ///     Key:UserPermission-Userid 保存用户权限值
        /// </summary>
        /// <param name="key">唯一关键字</param>
        /// <param name="data">数据</param>
        public static void SetCache(string key, object data)
        {
            SetCache(key, data, DateTimeOffset.Now.AddMinutes(30));
        }

        /// <summary>
        ///     获取本地缓存中的数据
        ///     Key:User-Userid 保存用户主键
        ///     Key:UserPermission-Userid 保存用户权限值
        /// </summary>
        /// <param name="key">唯一标识</param>
        /// <returns>缓存中的数据，NULL表示不存在</returns>
        public static object GetCache(string key)
        {
            return LocalMemory.Get(key);
        }
    }
}